import Vue from 'vue'
import { Notification } from 'element-ui';

export default ({ app, route }, inject) => inject("app", {
	
	// 分页条数
	limit: 10,
	
	// App名称
	appName: "AI哈哈",
	
	// 接口访问地址
	appList() { return "https://api.sora13.com"; },
	
	// 获取token
	getToken() {
		if (this.isLogin()) {
			return this.getUserInfo().token;
		} else {
			return "";
		}
	},

	// 获取请求头
	getRequestHeaders(e) {
		return e.header || { "authorization": (e.token || this.getToken()) }
	},

	// 网络请求方法
	ajax(e) {
		let _this = this;
		return new Promise((resolve, reject) => {
			// 关于加载提示
			if (typeof e.load == "object") e.load.load = true;
			
			// 关于是否修改url
			if (e.changeUrl && e.data) {
				let nowParams = JSON.parse(JSON.stringify(route.query));
				let dataParams = JSON.parse(JSON.stringify(e.data));
				let newUrlParams = Object.assign(nowParams, dataParams);
				app.router.replace({query: newUrlParams}).catch(err => {err;});
			}
			
			app.$axios({
				method: e.method || "GET",
				url: e.url,
				baseURL: e.baseURL || _this.appList(),
				data: e.method == "POST" ? e.data || {} : {},
				params: e.method != "POST" ? e.data || {} : {},
				headers: _this.getRequestHeaders(e),
				responseType: e.dataType || "json" // 默认json
			}).then(function (res) {
				if (typeof e.load == "object") e.load.load = false;
				
				if (res.data.code == 200) {
					resolve(res.data);
				} else if (res.data.code == 401) {
					e.showNotice !== false && Notification({title: "提示",message: "您的登录好像过期了！",type: "warning"});
					_this.removeUserInfo();
					app.router.push("/login");
				} else {
					reject(res.data);
					e.showNotice !== false && Notification({ title: "提示", message: (res && res.data && res.data.msg) ? res.data.msg : "网络错误！", type: "warning" });
				}
			}).catch(function (err) {
				if (typeof e.load == "object") e.load.load = false;
				reject(err);
				e.showNotice !== false && Notification({title: "提示",message: (err && err.data && err.data.msg) ? err.data.msg : "网络错误",type: "warning"});
			});
		});
	},
	
	// 将文件上传到服务器
	uploadFile(e) {
		let _this = this;
		return new Promise((resolve, reject) => {
			typeof e.load == "object" && (e.load.load = true);
			let formData = new FormData();
			formData.set("type", e.type || "other");
			formData.set("file", e.file);

			app.$axios({
				url: "/admin/basis/upload",
				method: "post",
				baseURL: _this.appList(),
				data: formData,
				headers: _this.getRequestHeaders(e),
				responseType: "json" // 默认json
			}).then(function (res) {
				typeof e.load == "object" && (e.load.load = false);
				
				if (res.data.code == 200) {
					resolve(res.data);
				} else if (res.data.code == 401) {
					_this.removeUserInfo();
					Notification({title: "提示",message: "您的登录好像过期了！",type: "warning"});
					app.router.push("/login");
					reject(res.data);
				} else {
					reject(res.data);
				}
			}).catch(function (err) {
				typeof e.load == "object" && (e.load.load = false);
				reject(res.data);
			});
		});
	},

	// 将字符串时间转换为时间戳
	getDateTimeStamp(dateStr) {
		return Date.parse(("" + dateStr).replace(/-/gi, "/"));
	},

	// 数据库时间转换为普通的时间戳
	mysqlTimeto(time) {
		let myDate = typeof time === "number" ? new Date(time) : new Date(time + "+0800");
		if (myDate == "Invalid Date") {
			time = time.replace(/T/g, " "); //去掉T
			time = time.replace(/-/g, "/");
			time = time.replace(/\.\d+/, " "); //去掉毫秒
			myDate = new Date(time + "+0800");
			return myDate;
		} else {
			return myDate;
		}
	},

	// 数据库时间转换成时间戳或者MM/DD
	toTime(strTime, type) {
		let myDate;
		if (strTime) {
			myDate = this.mysqlTimeto(strTime);
		} else {
			myDate = new Date();
		}

		let year = myDate.getFullYear();
		let month = myDate.getMonth() + 1;
		if (month < 10) {
			month = "0" + month;
		}
		let day = myDate.getDate();
		if (day < 10) {
			day = "0" + day;
		}
		let hours = myDate.getHours();
		if (hours < 10) {
			hours = "0" + hours;
		}
		let minute = myDate.getMinutes();
		if (minute < 10) {
			minute = "0" + minute;
		}
		let second = myDate.getSeconds();
		if (second < 10) {
			second = "0" + second;
		}

		if (type == "MM/DD") {
			return month + "/" + day;
		} else if (type == "YYYY/MM/DD hh:mm") {
			return year + "/" + month + "/" + day + " " + hours + ":" + minute;
		} else if (type == "YYYY/MM/DD hh:mm:ss") {
			return (year + "/" + month + "/" + day + " " + hours + ":" + minute + ":" + second);
		} else if(type == "YYYY-MM-DD hh:mm:ss") {
			return (year + "-" + month + "-" + day + " " + hours + ":" + minute + ":" + second);
		} else if (type == "MM/DD hh:mm") {
			return month + "/" + day + " " + hours + ":" + minute;
		}  else if (type == "MM/DD") {
			return month + "/" + day;
		} else if (type == "MM/DD hh:mm:ss") {
			return month + "/" + day + " " + hours + ":" + minute + ":" + second;
		} else if (type == "YYYY/MM/DD") {
			return year + "/" + month + "/" + day;
		} else if (type == "YYYYMMDD") {
			return year + "" + month + "" + day;
		} else if (type == "YYYY-MM") {
			return year + "-" + month;
		} else if (type == "YYYY-MM-DD") {
			return year + "-" + month + "-" + day;
		} else if (type == "YYYY") {
			return year;
		} else if (type == "hh:mm") {
			return hours + ":" + minute;
		} else {
			return myDate;
		}
	},

	// 将时间转换为xx之前
	getDateDiff(dateStr) {
		//console.log(dateStr)
		let publishTime = this.getDateTimeStamp(dateStr) / 1000,
			d_seconds,
			d_minutes,
			d_hours,
			d_days,
			timeNow = parseInt(new Date().getTime() / 1000),
			d,
			date = new Date(publishTime * 1000),
			Y = date.getFullYear(),
			M = date.getMonth() + 1,
			D = date.getDate(),
			H = date.getHours(),
			m = date.getMinutes(),
			s = date.getSeconds();
		//小于10的在前面补0
		if (M < 10) {
			M = "0" + M;
		}
		if (D < 10) {
			D = "0" + D;
		}
		if (H < 10) {
			H = "0" + H;
		}
		if (m < 10) {
			m = "0" + m;
		}
		if (s < 10) {
			s = "0" + s;
		}

		d = timeNow - publishTime;
		d_days = parseInt(d / 86400);
		d_hours = parseInt(d / 3600);
		d_minutes = parseInt(d / 60);
		d_seconds = parseInt(d);

		if (d_days > 0 && d_days < 2) {
			return d_days + "天前";
		} else if (d_days <= 0 && d_hours > 0) {
			return d_hours + "小时前";
		} else if (d_hours <= 0 && d_minutes > 0) {
			return d_minutes + "分钟前";
		} else if (d_seconds < 60) {
			if (d_seconds <= 0) {
				return "刚刚";
			} else {
				return d_seconds + "秒前";
			}
		} else if (d_days >= 2 && d_days < 30) {
			return M + "-" + D + " " + H + ":" + m;
		} else if (d_days >= 30) {
			return Y + "-" + M + "-" + D + " " + H + ":" + m;
		}
	},

	// 获取用户信息
	getUserInfo() {
		let userInfo = app.$cookies.get("userInfo");
		return userInfo || null;
	},

	// 设置用户信息
	setUserInfo(data) {
		app.$cookies.set("userInfo", JSON.stringify(data))
	},

	// 删除用户信息
	removeUserInfo() {
		app.$cookies.remove(`userInfo`);
	},

	// 判断是否登录
	isLogin() {
		let userInfo = app.$cookies.get(`userInfo`);
		if (userInfo) {
			return true;
		} else {
			return false;
		}
	},

	// 转换数字
	castNum(num) {
		if (num == null || num == undefined || num == "") {
			return 0;
		} else if (num < 10000) {
			return num;
		} else if (num >= 10000 && num < 100000000) {
			let newNum = (num / 10000).toFixed(1) + "万";
			return newNum;
		} else if (num >= 100000000 && num < 10000000000000000) {
			let newNum = (num / 100000000).toFixed(2) + "亿";
			return newNum;
		} else if (num >= 10000000000000000 && num < 1000000000000000000000000) {
			let newNum = (num / 10000000000000000).toFixed(2) + "亿亿";
			return newNum;
		} else {
			let newNum = "亿亿以上+";
			return newNum;
		}
	},

	// 读取当前登录时的账号密码、是否保存密码、是否正式服
	getUserPass() {
		let data = localStorage.getItem(`App_Username`);
		if (data) {
			return JSON.parse(data);
		} else {
			return {
				save: true,
				username: "",
				password: "",
				api: "prod"
			};
		}
	},

	// 写当前登录时的账号密码、是否保存密码、是否正式服
	setUserPass(e) {
		localStorage.setItem(`App_Username`,JSON.stringify(e));
	},

	// 删除当前登录时的账号密码、是否保存密码、是否正式服
	removeUserPass(e) {
		localStorage.removeItem(`App_Username`);
	},

	// 获取一个日期范围内的所有日期，入参为Date对象
	gainAllDateBetRange(startDate, endDate) {
		let dateArr = [];
		let startTime = new Date(startDate * 1000).getTime(); // 获取开始日期的毫秒数
		let endTime = new Date(endDate * 1000).getTime(); // 获取结束日期的毫秒数
		let oneTime = 24 * 60 * 60 * 1000; // 一天的毫秒数
		for (let time = startTime; time <= endTime;) {
			dateArr.push(this.dateFormat(new Date(time))); // 将格式化后的时间存入结果数组
			time += oneTime; // 每次加一天
		}
		return dateArr;
	},

	// 时间格式化
	dateFormat(date) {
		let year = date.getFullYear() + "-";
		let month =(date.getMonth() + 1 < 10? "0" + (date.getMonth() + 1): date.getMonth() + 1) + "-";
		let day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
		return year + month + day;
	},

	// 将秒时间转换为时分秒
	secondToDuration(time, zh, hours) {
		let second = parseInt(time);
		if (isNaN(second)) {
			return "-";
		}
			
		if (hours || time >= 3600) {
			let returnHours = Math.floor(time / 3600);
			let suprSecond = time % 3600;
			let returnMinute = Math.floor(suprSecond / 60);
			let returnSecond = Math.floor(suprSecond % 60);
			if (returnHours < 10) {
				returnHours = "0" + returnHours;
			}
			if (returnMinute < 10) {
				returnMinute = "0" + returnMinute;
			}
			if (returnSecond < 10) {
				returnSecond = "0" + returnSecond;
			}
			
			if (zh) {
				return `${returnHours}时${returnMinute}分${returnSecond}秒`;
			} else {
				return `${returnHours}:${returnMinute}:${returnSecond}`;
			}
		} else {
			let returnMinute = Math.floor(time / 60);
			let returnSecond = Math.floor(time % 60);
			if (returnMinute == -1 || returnSecond == -1) {
				return "-";
			}
			
			if (returnMinute < 10) {
				returnMinute = "0" + returnMinute;
			}
			if (returnSecond < 10) {
				returnSecond = "0" + returnSecond;
			}
			
			if (zh) {
				return `${returnMinute}分${returnSecond}秒`;
			} else {
				return `${returnMinute}:${returnSecond}`;
			}
		}
	},
	
	// 或者某某之间的随机数
	getRandomInt(min, max) {
		return Math.floor(Math.random() * (max - min + 1)) + min;
	},
	
});
